package com.webchat.connect.messagequeue.consumer.service;


import com.webchat.common.constants.ConnectConstants;
import com.webchat.common.enums.VideoSDPMessageType;
import com.webchat.common.util.JsonUtil;
import com.webchat.connect.service.AccountService;
import com.webchat.connect.service.GroupVideoBizService;
import com.webchat.connect.websocket.handler.GroupVideoWebSocketEndPointServletHandler;
import com.webchat.domain.vo.request.mess.VideoChatMessageRequestVO;
import com.webchat.domain.vo.request.mess.VideoUserChangeMessageVO;
import com.webchat.domain.vo.response.UserBaseResponseInfoVO;
import com.webchat.domain.vo.response.mess.VideoChatMessageResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


@Slf4j
@Service
public class GroupVideoUserChangeConsumeService {


    @Autowired
    private GroupVideoBizService groupVideoBizService;
    @Autowired
    private AccountService accountService;

    /**
     * 处理群聊多人音视频通话，用户上线下通知
     *
     * 1、获取当前群组音视频房间所有在线用户
     * 2、推送当前变更用户给所有在线成员
     *
     * @param messageJson
     */
    public void consume(String messageJson) {

        log.info("群聊多人音视频用户上/下线消息:{}", messageJson);

        VideoUserChangeMessageVO message = JsonUtil.fromJson(messageJson, VideoUserChangeMessageVO.class);
        String groupId = message.getGroupId();
        String eventUserId = message.getEventUserId();
        // 1、获取当前群组音视频房间所有在线用户
        Set<String> onlineUsers = groupVideoBizService.getOnlineUserIds(message.getGroupId());
        if (CollectionUtils.isEmpty(onlineUsers)) {
            return;
        }
        Map<String, UserBaseResponseInfoVO> onlineUserMaps = accountService.batchGet(onlineUsers);
        Map<String, String> onlineUsernames = onlineUserMaps.entrySet().stream()
                .filter(entry -> entry.getValue() != null) // 确保UserBaseResponseInfoVO对象不为null
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue().getUserName()
                ));
        VideoChatMessageResponseVO chatMessage = new VideoChatMessageResponseVO();
        chatMessage.setUserId(eventUserId);
        chatMessage.setOnlineUserIds(onlineUsers);
        chatMessage.setOnlineUsernames(onlineUsernames);
        chatMessage.setType(ObjectUtils.equals(message.getIsOnline(), true) ?
                VideoSDPMessageType.online.name() : VideoSDPMessageType.offline.name());
        String pushMessage = JsonUtil.toJsonString(chatMessage);
        // 2、推送当前变更用户给所有在线成员
        for (String onlineUser : onlineUsers) {
            WebSocketSession session = GroupVideoWebSocketEndPointServletHandler.getSession(groupId, onlineUser);
            if (session == null || !session.isOpen()) {
                continue;
            }
            try {
                session.sendMessage(new TextMessage(pushMessage));
            } catch (IOException e) {
                // TODO 策略：例如：重拾
            }
        }
    }
}
